﻿using MediatR;
using SuYuanRabbit.Domain.Entities.RBAC;
using SuYuanRabbit.ErrorCode;
using SuYuanRabbit.Infrastructure.Interfaces;
using SuYuanRabbit.ReadAPI.Applications.Commands.Users;
using SuYuanRabbit.ReadAPI.Dtos.Response;

namespace SuYuanRabbit.ReadAPI.Applications.CommandsHanders.Users
{
    /// <summary>
    /// 查询用户命令处理器
    /// </summary>
    public class QueryUserCommandHander : IRequestHandler<QueryUserCommand, PaggingResult<QueryUserDto>>
    {
        private readonly IBaseRepository<User> userRepository;
        private readonly IBaseRepository<Role> roleRepository;
        private readonly IBaseRepository<RoleUser> ru_Repository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="roleRepository">角色仓储</param>
        /// <param name="ru_Repository">角色用户仓储</param>
        public QueryUserCommandHander(IBaseRepository<User> userRepository, IBaseRepository<Role> roleRepository, IBaseRepository<RoleUser> ru_Repository)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.ru_Repository = ru_Repository;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<PaggingResult<QueryUserDto>> Handle(QueryUserCommand request, CancellationToken cancellationToken)
        {
            var users_ = await userRepository.FindAsync(x => x.IsLocked != true);
            if (!string.IsNullOrEmpty(request.UserNickName))
            {
                users_ = users_.Where(x => x.UserNickName.Contains(request.UserNickName));
            }
            if (!string.IsNullOrEmpty(request.UserPhone))
            {
                users_ = users_.Where(x => x.UserPhone.Contains(request.UserPhone));
            }
            var roles_ = await roleRepository.GetAll();
            var roleUsers_ = await ru_Repository.GetAll();
            var user = from a in users_
                       join b in roleUsers_
                       on a.UserId equals b.UserId
                       join c in roles_
                       on b.RoleId equals c.RoleId
                       select new QueryUserDto
                       {
                           RoleName = c.RoleName,
                           UserEmail = a.UserEmail,
                           UserId = a.UserId,
                           UserPhone = a.UserPhone,
                           UserNickName = a.UserNickName,
                       };
            int count = user.Count();
            int pageCount = (int)Math.Ceiling(count / (double)request.PageSize);
            int skip = (request.PageIndex - 1) * request.PageSize;
            user = user.OrderByDescending(x => x.UserId).Skip(skip).Take(request.PageSize);
            return await Task.FromResult(new PaggingResult<QueryUserDto>
            {
                TotalCount = count,
                TotalPage = pageCount,
                Data = user.ToList()
            });
        }
    }
}
